'use strict';

const uidObj = require('uni-id');
const {
	XMLParser
} = require("fast-xml-parser");
const db = uniCloud.database();
const {
	mainSpaceId
} = require('config-main-space')
exports.main = async (event, context) => {
	let response = {
		mpserverscssComposedResponse: true,
		statusCode: 200,
		headers: {
			'content-type': 'text/xml;charset=utf-8'
		},
		body: `<xml><return_code><![CDATA[FAILD]]></return_code><return_msg><![CDATA[异常回调]]></return_msg></xml>`
	};
	let data = event.body
	if (event.isBase64Encoded) {
		data = new Buffer(data, 'base64').toString();
	}
	const path = event.path;
	let res = {};

	let notifyType = 'payment';
	let payObj = {
		name: '微信支付',
		way: 'wxpay'
	};
	switch (path) {
		case '/':
		case '/wxpay':
		case '/wxpay-app':
		case '/wxpay-h5wx':
			const parser = new XMLParser();
			res = parser.parse(data);
			res = res.xml
			try {
				//特殊处理transaction_id
				let transaction_ids = data.split('<transaction_id><![CDATA[')
				if (transaction_ids.length > 0) {
					let transaction_id = transaction_ids[1].split("]]></transaction_id>")[0]
					res.transaction_id = transaction_id
				}
			} catch (e) {

			}

			break;
		case '/alipay':
		case '/alipay-app':
			var queryArr = data.split("&");
			queryArr.forEach(function(item) {
				var key = item.split("=")[0];
				var value = item.split("=")[1];
				res[key] = value;
			});
			res.total_fee = res.total_amount * 100
			res.transaction_id = res.trade_no
			payObj.name = '支付宝支付';
			payObj.way = 'alipay';
			break;
		default:
			break;
	}

	if (res && (res.return_code == 'SUCCESS' || res.result_code == 'SUCCESS' || res.trade_status ==
			'TRADE_SUCCESS') && notifyType == 'payment') {
		let outTradeNo = res.out_trade_no
		let totalFee = res.total_fee
		let transactionId = res.transaction_id
		let openid = res.openid

		let payRes = await db.collection('wmzmall-order-pay')
			.where({
				order_id: outTradeNo
			})
			.get();

		if (!(payRes && payRes.data && payRes.data.length == 1)) {
			uniCloud.logger.info(`支付号[${outTradeNo}]不存在`);
			return response;
		}

		const pay = payRes.data[0];
		if (pay.pay_state === '已付款') {
			response.body =
				`<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>`;
			uniCloud.logger.info("已付款");
			return response;
		}
		const uid = pay.create_uid;
		let entitlement_id = pay.entitlement_id
		let vip_id = pay.vip_id
		let memberConfig = {}
		if (vip_id) {
			memberConfig = await db.collection('wmzmall-member-config').doc(vip_id).get();
			memberConfig = memberConfig.data[0]
		}

		let arrival_money = memberConfig.arrival_money
		let vip_name = memberConfig.name

		const nowdate = new Date().getTime();

		let nowtime = toDateUTC8(new Date());
		let plus_time = new Date();
		// 1年会员有效期
		plus_time.setFullYear(plus_time.getFullYear() + 1);

		// 写入付费会员数据
		await db.collection('wmzmall-member-paying').add({
			member_uid: uid,
			app_id: pay.app_id,
			shop_id: pay.shop_id,
			pay_id: outTradeNo,
			pay_title: vip_name,
			pay_money: totalFee,
			pay_openid: openid,
			pay_way: payObj.way,
			pay_original: payObj.name,
			pay_preid: pay.pay_preid,
			pay_notify: event,
			pay_time: nowdate,
			pay_no: transactionId,
			pay_yy_mm: nowtime.getFullYear() + '-' + (nowtime.getMonth() + 1),
			pay_yy_mm_dd: nowtime.getFullYear() + '-' + (nowtime.getMonth() + 1) + '-' + nowtime
				.getDate(),
			expire_time: plus_time.getTime(),
			pay_state: '已付款',
			version: 1,
			create_time: nowdate,
			create_uid: uid
		});

		// 修改订单支付数据
		await db.collection('wmzmall-order-pay').where({
			order_id: outTradeNo
		}).update({
			version: db.command.inc(1),
			pay_state: '已付款',
			pay_notify: event,
			pay_time: nowdate,
			pay_no: transactionId,
			pay_openid: openid
		});

		// todo 已付费会员，再次支付
		// 	1. 会员如果有效，当前的过期时间 = 上一次过期时间 +1年
		// 	2. 会员如果无效，当前的过期时间 = 现在的时间 +1年
		const userRes = await db.collection('wmzmall-member')
			.doc(uid)
			.get();
		// 用户
		const user = userRes.data[0];
		let member_amount = 0
		if (user.member_amount) {
			member_amount = user.member_amount * 1 + arrival_money * 100
		}
		// 修改付费会员数据 
		const memberRes = await db.collection('wmzmall-member').doc(uid).update({
			member_monetary: db.command.inc(totalFee),
			is_plus: vip_name,
			is_plus_id: vip_id,
			plus_time: plus_time.getTime(),
			member_amount: member_amount,
			vip_price_discount: memberConfig.vip_price_discount,
			double_integral: memberConfig.double_integral,
			partner: memberConfig.partner,
		});




		if (entitlement_id) {
			let entitlementOrder = await db.collection('wmz-entitlement').doc(entitlement_id).get()
			entitlementOrder = entitlementOrder.data[0]
			let coupon_data = entitlementOrder.coupon_data
			for (var i in coupon_data) {
				coupon_data[i].goods_type = "mobile_coupon"
				coupon_data[i].order_id = uid
				coupon_data[i].user_id = uid
				coupon_data[i].status = '未使用'
				coupon_data[i].app_id = user.app_id
				coupon_data[i].create_time = new Date().getTime()
				let cRes = await db.collection('wmz-entitlement-coupon').add(coupon_data[i])
			}
		}


		let title = '收款';
		let cate = '会员';
		let type = 0;
		let appId = user.app_id;
		let auto_deliver
		let appletInfoData = await db.collection('wmz-applet-info').doc(appId).get()
		appletInfoData = appletInfoData.data[0]
		if (appletInfoData && appletInfoData.auto_deliver) {
			auto_deliver = appletInfoData.auto_deliver
		}
		let shopId = user.shop_id;
		let orderNo = transactionId;
		let way = payObj.name;
		let payMoney = totalFee;
		let shopie = {
			app_id: appId,
			shop_id: shopId,
			order_no: orderNo,
			title: title,
			cate: cate,
			type: type,
			way: way,
			money: payMoney,
			creator_id: uid,
			create_time: new Date().getTime(),
			auto_deliver: auto_deliver
		};
		let addShopieResult = await db.collection('wmzmall-shopie').add(shopie);
		let tdb = uniCloud.database({
			provider: 'tencent',
			spaceId: mainSpaceId
		})
		await tdb.collection('wmzmall-shopie').add(shopie)

		if (payObj.way == 'wxpay') {
			response.body =
				`<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>`;
		} else if (payObj.way = 'alipay') {
			response.headers['content-type'] = 'text/plain';
			response.body = 'success';
		}
	}

	if (notifyType == 'refund') {
		if (payObj.way = 'alipay') {
			response.headers['content-type'] = 'text/plain';
			response.body = 'success';
		}
	}

	uniCloud.logger.info(res);
	uniCloud.logger.info(response);

	return response;
};


/**
 * 将 UTC+0 转换为 UTC+8
 */
function toDateUTC8(date) {
	// 小时 UTC+0 转换为 UTC+8
	date.setHours(date.getHours() + 8);
	return date;
}